import { initDynamicRoutes } from "../router.js"
export default {
  template: `
    <el-form :model="form" ref="form" :rules="rules" label-width="80px" :inline="false" size="normal">
      <el-form-item label="用户名">
        <el-input ref="mark" v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  `,
  data() {
    return {
      form: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { required: true, message: '长度在 3 到 5 个字符', trigger: 'change' }
        ],
      }
    }
  },
  mounted() {
    this.$refs['mark'].focus()
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        let res = null;
        switch (this.form.username) {
          case "test":
            res = await fetch(
              "./test.json",
            ).then((res) => res.json());
            this.divertByUsername(res)
            break;
          case "admin":
            res = await fetch(
              "./admin.json",
            ).then((res) => res.json());
            this.divertByUsername(res)
            break;
          default:
            break;
        }
      })
    },
    divertByUsername(res) {
      if (res.meta.status !== 200) return this.$message.error('登录失败')
      this.$store.commit('setRightList', { data: res.rights })
      this.$store.commit('setUserNmae', { username: res.data.username })
      sessionStorage.setItem('jauthToken', res.data.token)
      initDynamicRoutes()
      this.$router.push('/')
      this.$message.success('登录成功')
    },
    resetForm() {
      this.$refs.form.resetFields()
    }
  },
}